package edu.kit.los.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.esxx.js.protocol.GAEConnectionManager;

import upcoming.client.Event;
import edu.kit.los.event.StandardEvent;

/**
 * Servlet, das Anfragen an Upcoming verwaltet.
 * @author Felix Kiechle, Benedikt Fuss  AIFB@BKIT
 * 
 */
public class UpcomingLookup extends HttpServlet{

	
	/**
	 * ID für Serialisierung
	 */
	private static final long serialVersionUID = -5150565780947874836L;

	/**
	 * Führt mit Hilfe der Upcoming-Java Api einen Lookup bei Upcoming durch
	 * und schreibt das Ergebnis als XML/RDF auf den Outputstream.
	 * 
	 * @param HttpservletRequest request      
	 * @param HttpServletResponse response
	 * @throws ServletException
	 * @throws IOExceptionn
	 * 	 
	*/
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String query = request.getParameter("query");
		OutputStream out = response.getOutputStream();
		HttpParams httpParams = new BasicHttpParams();
		edu.kit.los.Model model = new edu.kit.los.Model();
		response.setContentType(Servlet.contentType_RDF);
		ClientConnectionManager connectionManager = new GAEConnectionManager();
		org.apache.http.client.HttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
		upcoming.client.Client client = new upcoming.client.Client(httpClient, "6f0d8fce85");
		List<upcoming.client.Event> upcevent = new LinkedList<upcoming.client.Event>();
		upcevent = client.findEvents(query);
		for(Event event : upcevent){
			model.addEvent(new StandardEvent(event));
		}
		model.writeRDF(out);	
	}
}
